import { defineStore } from 'pinia';
import { Local } from '/@/utils/storage';
import { getUserInfo } from '../api/login';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
  state: (): UserInfosState => ({
    userInfos: {
      photo: '',
      name: '',
      mobile: '',
      role: '',
      id: '',
      station: '',
      super_admin: false,
      permissions: [],
    },
  }),
  actions: {
    async setUserInfos() {
      // 存储用户信息到浏览器缓存
      if (Local.get('userInfo')) {
        this.userInfos = Local.get('userInfo');
      } else {
        const userInfos = <UserInfos>await this.getApiUserInfo();
        this.userInfos = userInfos;
      }
    },
    async getApiUserInfo() {
      const data = await getUserInfo();
      const userInfo = {
        id: data.id,
        name: data.name,
        mobile: data.mobile,
        role: data.role_id,
        super_admin: data.super_admin,
        // permissions: data.permissions.map((item: any) => item.key),
        station: data.station,
        photo: data.super_admin
          ? 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500'
          : 'https://img2.baidu.com/it/u=2370931438,70387529&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
        time: Date.now(),
      };

      // Local.set('userInfo', userInfo);
      return userInfo;
    },
  },
});
